<template>
  <div class="orders-page">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-container">
        <div class="logo-section">
          <h1 class="store-title">
            <span class="leaf-icon"><i class="fas fa-shopping-cart"></i></span>
            我的订单
          </h1>
        </div>
      </div>
    </header>

    <div class="orders-container">
      <!-- 订单筛选 -->
      <div class="orders-filter">
        <div class="filter-tabs">
          <div
            v-for="tab in orderTabs"
            :key="tab.status"
            :class="['filter-tab', { active: activeTab === tab.status }]"
            @click="handleTabClick(tab.status)"
          >
            <span class="tab-name">{{ tab.name }}</span>
            <span v-if="tab.count > 0" class="tab-count">{{ tab.count }}</span>
          </div>
        </div>
        
        <div class="filter-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单商品..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="timeFilter" placeholder="时间筛选" class="time-select">
            <el-option label="全部时间" value="all" />
            <el-option label="最近一个月" value="1month" />
            <el-option label="最近三个月" value="3months" />
            <el-option label="最近一年" value="1year" />
          </el-select>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list">
        <div v-if="filteredOrders.length === 0" class="empty-orders">
          <div class="empty-icon">📦</div>
          <p class="empty-text">暂无订单</p>
          <el-button type="primary" @click="goToHome">去购物</el-button>
        </div>

        <div v-else class="order-items">
          <div
            v-for="order in paginatedOrders"
            :key="order.id"
            class="order-item"
          >
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.orderNumber }}</span>
                <span class="order-time">下单时间：{{ formatOrderTime(order.createTime) }}</span>
              </div>
              <div class="order-status">
                <!-- 退款标记 -->
                <span 
                  v-if="hasPendingRefund(order.id)" 
                  class="refund-badge"
                >
                  退款审核中
                </span>
                <span :class="['status-badge', getStatusClass(order.status)]">
                  {{ getStatusText(order.status) }}
                </span>
              </div>
            </div>

            <!-- 订单商品 -->
            <div class="order-products">
              <div
                v-for="item in order.items"
                :key="item.id"
                class="product-item"
              >
                <img :src="item.image" :alt="item.name" class="product-image" />
                <div class="product-info">
                  <h4 class="product-name">{{ item.name }}</h4>
                  <p class="product-spec">{{ item.weight }}kg · {{ getCategoryName(item.category) }}</p>
                </div>
                <div class="product-quantity">×{{ item.quantity }}</div>
                <div class="product-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </div>

            <!-- 订单统计 -->
            <div class="order-summary">
              <div class="summary-info">
                <span>共 {{ getTotalQuantity(order) }} 件商品</span>
                <span>合计：</span>
                <span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <div class="action-buttons">
                <!-- 待付款订单操作 -->
                <template v-if="order.status === 0">
                  <el-button type="primary" @click="payOrder(order)">立即支付</el-button>
                  <el-button @click="cancelOrder(order.id)">取消订单</el-button>
                  <div class="payment-timer" v-if="order.paymentTimer > 0">
                    <span class="timer-text">剩余支付时间：</span>
                    <span class="timer-count">{{ formatTimer(order.paymentTimer) }}</span>
                  </div>
                </template>

                <!-- 已付款订单操作 -->
                <template v-else-if="order.status === 1">
                  <el-button @click="cancelOrderWithReason(order.id)">取消订单</el-button>
                  <el-button @click="contactCustomerService">联系客服</el-button>
                  <el-button @click="viewLogistics(order.id)">查看物流</el-button>
                </template>

                <!-- 已发货订单操作 -->
                <template v-else-if="order.status === 2">
                  <el-button type="primary" @click="confirmReceipt(order.id)">确认收货</el-button>
                  <el-button @click="cancelOrderWithReason(order.id)">取消订单</el-button>
                  <el-button @click="viewLogistics(order.id)">查看物流</el-button>
                  <el-button @click="contactCustomerService">联系客服</el-button>
                </template>

                <!-- 已完成订单操作 -->
                <template v-else-if="order.status === 3">
                  <el-button 
                    v-if="!order.hasRated" 
                    type="primary" 
                    @click="gradeOrder(order)"
                  >
                    追加评分
                  </el-button>
                  <el-button 
                    v-else 
                    type="success" 
                    disabled
                  >
                    已评分 ({{ order.rating }}星)
                  </el-button>
                  <el-button type="primary" @click="buyAgain(order)">再次购买</el-button>
                  <el-button 
                    v-if="!hasPendingRefund(order.id)" 
                    @click="applyRefund(order.id)"
                  >
                    申请退款
                  </el-button>
                  <el-button 
                    v-else 
                    type="danger" 
                    @click="cancelRefund(order.id)"
                  >
                    取消退款
                  </el-button>
                  <el-button @click="deleteOrder(order.id)">删除订单</el-button>
                </template>

                <!-- 已取消订单操作 -->
                <template v-else-if="order.status === 4">
                  <el-button type="primary" @click="buyAgain(order)">再次购买</el-button>
                  <el-button @click="deleteOrder(order.id)">删除订单</el-button>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section" v-if="filteredOrders.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredOrders.length"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="showPaymentDialog"
      title="订单支付"
      width="500px"
    >
      <div class="payment-dialog">
        <div class="payment-info">
          <div class="payment-amount">
            <span>支付金额：</span>
            <span class="amount">¥{{ currentOrder?.totalAmount.toFixed(2) }}</span>
          </div>
          <div class="payment-method">
            <span>支付方式：</span>
            <span>{{ getPaymentMethodName(currentOrder?.paymentMethod) }}</span>
          </div>
        </div>
        <div class="payment-timer">
          <span>支付剩余时间：</span>
          <span class="timer">{{ formatTimer(paymentTimer) }}</span>
        </div>
        <div class="payment-actions">
          <el-button @click="showPaymentDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmOrderPayment">确认支付</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 申请退款对话框 -->
    <el-dialog
      v-model="showRefundDialog"
      title="申请退款"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="refund-dialog">
        <el-form :model="refundForm" label-width="100px">
          <!-- 订单信息 -->
          <el-form-item label="订单信息">
            <div class="order-refund-info">
              <div class="order-number">订单号：{{ currentRefundOrder?.orderNumber }}</div>
              <div class="order-amount">订单金额：¥{{ currentRefundOrder?.totalAmount.toFixed(2) }}</div>
            </div>
          </el-form-item>
          
          <!-- 退款原因 -->
          <el-form-item label="退款原因" required>
            <el-select 
              v-model="refundForm.reason" 
              placeholder="请选择退款原因"
              style="width: 100%"
            >
              <el-option
                v-for="reason in refundReasons"
                :key="reason.value"
                :label="reason.label"
                :value="reason.value"
              />
            </el-select>
          </el-form-item>
          
          <!-- 退款说明 -->
          <el-form-item label="退款说明" required>
            <el-input
              v-model="refundForm.description"
              type="textarea"
              :rows="4"
              placeholder="请详细描述退款原因和问题..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          
          <!-- 图片上传 -->
          <el-form-item label="问题图片">
            <div class="image-upload-section">
              <el-upload
                action="#"
                :file-list="refundForm.images"
                :before-upload="handleImageUpload"
                :show-file-list="false"
                accept="image/*"
                multiple
              >
                <el-button type="primary" :icon="Plus">
                  上传图片
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    最多可上传5张图片，每张不超过2MB
                  </div>
                </template>
              </el-upload>
              
              <!-- 图片预览 -->
              <div v-if="refundForm.images.length > 0" class="image-preview-list">
                <div
                  v-for="(image, index) in refundForm.images"
                  :key="image.id"
                  class="image-preview-item"
                >
                  <img :src="image.url" alt="问题图片" />
                  <div class="image-actions">
                    <el-button
                      type="danger"
                      :icon="Delete"
                      circle
                      size="small"
                      @click="removeImage(index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="showRefundDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRefund" style="width: 120px;">
          提交申请
        </el-button>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog
      v-model="showRatingDialog"
      title="商品评价"
      width="500px"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <div class="rating-dialog-content">
        <div class="rating-header">
          <h3>请为本次购物体验评分</h3>
          <p class="rating-subtitle">您的评价对我们很重要</p>
        </div>
        
        <div class="order-info-rating">
          <div class="order-products-rating">
            <div 
              v-for="item in currentRatingOrder?.items" 
              :key="item.id"
              class="product-item-rating"
            >
              <img :src="item.image" :alt="item.name" class="product-image-rating" />
              <div class="product-info-rating">
                <h4>{{ item.name }}</h4>
                <p>{{ item.weight }}kg × {{ item.quantity }}</p>
              </div>
            </div>
          </div>
        </div>

        <div class="rating-section">
          <div class="rating-title">商品满意度</div>
          <div class="rating-stars">
            <div class="rating">
              <input type="radio" id="star-5" name="star-radio" value="5" v-model="rating">
              <label for="star-5">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path>
                </svg>
              </label>
              <input type="radio" id="star-4" name="star-radio" value="4" v-model="rating">
              <label for="star-4">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path>
                </svg>
              </label>
              <input type="radio" id="star-3" name="star-radio" value="3" v-model="rating">
              <label for="star-3">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path>
                </svg>
              </label>
              <input type="radio" id="star-2" name="star-radio" value="2" v-model="rating">
              <label for="star-2">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path>
                </svg>
              </label>
              <input type="radio" id="star-1" name="star-radio" value="1" v-model="rating">
              <label for="star-1">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path pathLength="360" d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z"></path>
                </svg>
              </label>
            </div>
          </div>
          <div class="rating-text">
            <span v-if="rating === 0">请选择评分</span>
            <span v-else-if="rating === 1">非常不满意</span>
            <span v-else-if="rating === 2">不满意</span>
            <span v-else-if="rating === 3">一般</span>
            <span v-else-if="rating === 4">满意</span>
            <span v-else-if="rating === 5">非常满意</span>
          </div>
        </div>
        
        <div class="rating-actions">
          <el-button @click="showRatingDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitRating" 
            :disabled="rating === 0"
            class="submit-rating-btn"
          >
            {{ rating === 0 ? '请选择评分' : `提交${rating}星评价` }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 订单状态定义
const ORDER_STATUS = {
  PENDING: 0,      // 待付款
  PAID: 1,         // 已付款
  SHIPPED: 2,      // 已发货
  COMPLETED: 3,    // 已完成
  CANCELLED: 4    // 已取消
}

// 响应式数据
const activeTab = ref('all')
const searchKeyword = ref('')
const timeFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(5)
const showPaymentDialog = ref(false)
const currentOrder = ref(null)
const paymentTimer = ref(1800) // 30分钟
const refundApplications = ref([])

const showRefundDialog = ref(false)
const currentRefundOrder = ref(null)

const showRatingDialog = ref(false)  // 控制评分对话框显示
const currentRatingOrder = ref(null) // 存储当前评分的订单
const rating = ref(0)  // 存储评分值

const refundForm = ref({
  reason: '',
  description: '',
  images: []
})

// 检查订单是否有待处理的退款申请
const hasPendingRefund = (orderId) => {
  return refundApplications.value.some(app => 
    app.orderId === orderId && app.status === 'pending'
  )
}

// 订单数据
const orders = ref([
  {
    id: 1,
    orderNumber: 'NO202412010001',
    status: ORDER_STATUS.PENDING,
    createTime: '2024-12-01 10:30:00',
    totalAmount: 45.8,
    paymentMethod: 1,
    paymentTimer: 1500, // 剩余支付时间（秒）
    items: [
      {
        id: 1,
        name: '有机西红柿',
        price: 8.5,
        quantity: 2,
        weight: 1.2,
        category: 'vegetable',
        image: 'https://images.unsplash.com/photo-1546470427-e212d0d553c3?w=300&h=200&fit=crop'
      },
      {
        id: 2,
        name: '新鲜黄瓜',
        price: 6.0,
        quantity: 3,
        weight: 0.8,
        category: 'vegetable',
        image: 'https://images.unsplash.com/photo-1449300079327-02f967c1cdee?w=300&h=200&fit=crop'
      }
    ]
  },
  {
    id: 2,
    orderNumber: 'NO202411280001',
    status: ORDER_STATUS.PAID,
    createTime: '2024-11-28 14:20:00',
    totalAmount: 68.5,
    paymentMethod: 2,
    items: [
      {
        id: 3,
        name: '特价土鸡蛋',
        price: 18.8,
        quantity: 2,
        weight: 0.5,
        category: 'egg',
        image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=200&fit=crop'
      },
      {
        id: 4,
        name: '有机胡萝卜',
        price: 12.5,
        quantity: 1,
        weight: 1.0,
        category: 'vegetable',
        image: 'https://images.unsplash.com/photo-1445282768818-728615cc910a?w=300&h=200&fit=crop'
      }
    ]
  },
  {
    id: 3,
    orderNumber: 'NO202411250001',
    status: ORDER_STATUS.SHIPPED,
    createTime: '2024-11-25 09:15:00',
    totalAmount: 32.4,
    paymentMethod: 1,
    items: [
      {
        id: 5,
        name: '新鲜菠菜',
        price: 7.8,
        quantity: 2,
        weight: 0.5,
        category: 'vegetable',
        image: 'https://images.unsplash.com/photo-1576045057995-568f588f82fb?w=300&h=200&fit=crop'
      }
    ]
  },
  {
    id: 4,
    orderNumber: 'NO202411200001',
    status: ORDER_STATUS.COMPLETED,
    createTime: '2024-11-20 16:45:00',
    totalAmount: 56.2,
    paymentMethod: 2,
    hasRated: false, // 新增：是否已评分
    rating: 0, // 新增：评分值
    items: [
      {
        id: 6,
        name: '有机苹果',
        price: 15.9,
        quantity: 2,
        weight: 2.0,
        category: 'fruit',
        image: 'https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=300&h=200&fit=crop'
      }
    ]
  },
  {
    id: 5,
    orderNumber: 'NO202411150001',
    status: ORDER_STATUS.CANCELLED,
    createTime: '2024-11-15 11:20:00',
    totalAmount: 42.3,
    paymentMethod: 1,
    items: [
      {
        id: 7,
        name: '新鲜草莓',
        price: 22.8,
        quantity: 1,
        weight: 0.5,
        category: 'fruit',
        image: 'https://images.unsplash.com/photo-1464965911861-746a04b4bca6?w=300&h=200&fit=crop'
      }
    ]
  }
])

// 退款原因选项
const refundReasons = [
  { value: 'quality', label: '商品质量问题' },
  { value: 'damaged', label: '商品破损/损坏' },
  { value: 'wrong', label: '发错商品' },
  { value: 'missing', label: '商品漏发' },
  { value: 'not_match', label: '商品与描述不符' },
  { value: 'other', label: '其他原因' }
]

// 计算属性
const orderTabs = computed(() => {
  const allCount = orders.value.length
  const pendingCount = orders.value.filter(o => o.status === ORDER_STATUS.PENDING).length
  const paidCount = orders.value.filter(o => o.status === ORDER_STATUS.PAID).length
  const shippedCount = orders.value.filter(o => o.status === ORDER_STATUS.SHIPPED).length
  const completedCount = orders.value.filter(o => o.status === ORDER_STATUS.COMPLETED).length
  const cancelledCount = orders.value.filter(o => o.status === ORDER_STATUS.CANCELLED).length

  return [
    { status: 'all', name: '全部订单', count: allCount },
    { status: ORDER_STATUS.PENDING.toString(), name: '待付款', count: pendingCount },
    { status: ORDER_STATUS.PAID.toString(), name: '待发货', count: paidCount },
    { status: ORDER_STATUS.SHIPPED.toString(), name: '待收货', count: shippedCount },
    { status: ORDER_STATUS.COMPLETED.toString(), name: '已完成', count: completedCount },
    { status: ORDER_STATUS.CANCELLED.toString(), name: '已取消', count: cancelledCount }
  ]
})

const filteredOrders = computed(() => {
  let filtered = orders.value

  // 按状态筛选
  if (activeTab.value !== 'all') {
    filtered = filtered.filter(order => order.status === parseInt(activeTab.value))
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(order => 
      order.items.some(item => 
        item.name.toLowerCase().includes(keyword)
      )
    )
  }

  // 按时间筛选
  if (timeFilter.value !== 'all') {
    const now = new Date()
    let startDate = new Date()

    switch (timeFilter.value) {
      case '1month':
        startDate.setMonth(now.getMonth() - 1)
        break
      case '3months':
        startDate.setMonth(now.getMonth() - 3)
        break
      case '1year':
        startDate.setFullYear(now.getFullYear() - 1)
        break
    }

    filtered = filtered.filter(order => new Date(order.createTime) >= startDate)
  }

  return filtered
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 方法
const handleTabClick = (status) => {
  activeTab.value = status
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const getStatusText = (status) => {
  const statusMap = {
    [ORDER_STATUS.PENDING]: '待付款',
    [ORDER_STATUS.PAID]: '已付款',
    [ORDER_STATUS.SHIPPED]: '已发货',
    [ORDER_STATUS.COMPLETED]: '已完成',
    [ORDER_STATUS.CANCELLED]: '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
  const classMap = {
    [ORDER_STATUS.PENDING]: 'pending',
    [ORDER_STATUS.PAID]: 'paid',
    [ORDER_STATUS.SHIPPED]: 'shipped',
    [ORDER_STATUS.COMPLETED]: 'completed',
    [ORDER_STATUS.CANCELLED]: 'cancelled'
  }
  return classMap[status] || 'unknown'
}

const getCategoryName = (category) => {
  const categories = {
    vegetable: '蔬菜',
    fruit: '水果',
    egg: '禽蛋'
  }
  return categories[category] || category
}

const getTotalQuantity = (order) => {
  return order.items.reduce((sum, item) => sum + item.quantity, 0)
}

const formatOrderTime = (timeString) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

const formatTimer = (seconds) => {
  if (typeof seconds !== 'number' || seconds <= 0) return '00:00'
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const getPaymentMethodName = (methodId) => {
  const methods = {
    1: '微信支付',
    2: '支付宝',
    3: '银行转账'
  }
  return methods[methodId] || '未知'
}

const goToHome = () => {
  router.push('/buyer/index')
  // 这里应该使用路由跳转
  console.log('跳转到首页')
}

// 订单操作方法
const payOrder = (order) => {
  currentOrder.value = order
  paymentTimer.value = order.paymentTimer || 1800
  showPaymentDialog.value = true
}

const gradeOrder = (order) => { 
  // 检查是否已经评分过
  if (order.hasRated) {
    ElMessage.info('您已经对该订单评分过了')
    return
  }
  
  currentRatingOrder.value = order
  rating.value = 0 // 重置评分
  showRatingDialog.value = true
}

// 提交评分方法
const submitRating = async () => {
  try {
    if (rating.value === 0) {
      ElMessage.error('请选择评分')
      return
    }

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 更新订单的评分状态
    const orderIndex = orders.value.findIndex(o => o.id === currentRatingOrder.value.id)
    if (orderIndex !== -1) {
      orders.value[orderIndex].hasRated = true
      orders.value[orderIndex].rating = rating.value
    }
    
    showRatingDialog.value = false
    ElMessage.success(`评分成功！感谢您的${rating.value}星评价`)
    
  } catch (error) {
    ElMessage.error('评分失败，请重试')
  }
}

const confirmOrderPayment = async () => {
  try {
    // 模拟支付API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新订单状态
    const orderIndex = orders.value.findIndex(o => o.id === currentOrder.value.id)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = ORDER_STATUS.PAID
      orders.value[orderIndex].paymentTimer = 0
    }
    
    showPaymentDialog.value = false
    ElMessage.success('支付成功！')
  } catch (error) {
    ElMessage.error('支付失败，请重试')
  }
}

const cancelOrderWithReason = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '再想想',
      type: 'warning'
    })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = ORDER_STATUS.CANCELLED
    }
    
    ElMessage.success('订单已取消,费用退回至您的支付账户')
  } catch (error) {
    // 用户点击了取消
  }
}

const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '再想想',
      type: 'warning'
    })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = ORDER_STATUS.CANCELLED
    }
    
    ElMessage.success('订单已取消')
  } catch (error) {
    // 用户点击了取消
  }
}

// 申请退款方法
const applyRefund = (orderId) => {
  const order = orders.value.find(o => o.id === orderId)
  if (!order) return
  
  currentRefundOrder.value = order
  resetRefundForm()
  showRefundDialog.value = true
}

// 重置退款表单
const resetRefundForm = () => {
  refundForm.value = {
    reason: '',
    description: '',
    images: []
  }
}

// 处理图片上传
const handleImageUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    refundForm.value.images.push({
      id: Date.now(),
      url: e.target.result,
      file: file
    })
  }
  reader.readAsDataURL(file)
  return false // 阻止自动上传
}

// 删除图片
const removeImage = (index) => {
  refundForm.value.images.splice(index, 1)
}

// 提交退款申请
const submitRefund = async () => {
  try {
    // 验证表单
    if (!refundForm.value.reason) {
      ElMessage.error('请选择退款原因')
      return
    }
    
    if (!refundForm.value.description.trim()) {
      ElMessage.error('请填写退款说明')
      return
    }
    
    // 显示确认对话框
    await ElMessageBox.confirm('确定要提交退款申请吗？', '提交退款申请', {
      confirmButtonText: '确定提交',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建退款申请记录
    const refundApplication = {
      id: Date.now(),
      orderId: currentRefundOrder.value.id,
      orderNumber: currentRefundOrder.value.orderNumber,
      ...refundForm.value,
      createTime: new Date().toISOString(),
      status: 'pending', // pending, approved, rejected, cancelled
      statusText: '审核中'
    }
    
    // 保存到退款申请记录
    refundApplications.value.push(refundApplication)
    
    console.log('退款申请提交成功:', refundApplication)
    
    // 关闭对话框
    showRefundDialog.value = false
    ElMessage.success('退款申请已提交，请等待管理员审核')
    
  } catch (error) {
    // 用户取消提交
    console.log('用户取消提交退款申请')
  }
}

// 取消退款申请
const cancelRefund = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消退款申请吗？', '取消退款', {
      confirmButtonText: '确定取消',
      cancelButtonText: '再想想',
      type: 'warning'
    })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新退款申请记录状态
    const refundIndex = refundApplications.value.findIndex(app => 
      app.orderId === orderId && app.status === 'pending'
    )
    
    if (refundIndex !== -1) {
      refundApplications.value[refundIndex].status = 'cancelled'
      refundApplications.value[refundIndex].statusText = '已取消'
    }
    
    ElMessage.success('退款申请已取消')
  } catch (error) {
    // 用户点击了取消
  }
}

const confirmReceipt = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认收到商品了吗？', '确认收货', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消'
    })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = ORDER_STATUS.COMPLETED
    }
    
    ElMessage.success('收货确认成功！')
  } catch (error) {
    // 用户点击了取消
  }
}

const buyAgain = (order) => {
  // 跳转到支付页面并传递参数
  router.push({
    path: '/buyer/payFor',
    query: {
      orderData: JSON.stringify(order),
      source: 'buyAgain'
    }
  })
}

const deleteOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '删除订单', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    orders.value = orders.value.filter(o => o.id !== orderId)
    ElMessage.success('订单删除成功')
  } catch (error) {
    // 用户点击了取消
  }
}

const viewLogistics = (orderId) => {
  ElMessage.info('跳转到物流详情页面')
  console.log('查看物流:', orderId)
}

const contactCustomerService = () => {
  ElMessage.info('请联系客服热线：400-123-4567')
}

// 定时器更新支付倒计时
let timerInterval = null

onMounted(() => {
  timerInterval = setInterval(() => {
    orders.value.forEach(order => {
      if (order.status === ORDER_STATUS.PENDING && order.paymentTimer > 0) {
        order.paymentTimer--
        if (order.paymentTimer <= 0) {
          order.status = ORDER_STATUS.CANCELLED
          ElMessage.warning(`订单 ${order.orderNumber} 因超时未支付已自动取消`)
        }
      }
    })
  }, 1000)
})

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
})
</script>

<style scoped>
.orders-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.page-header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.store-title {
  color: #10b981;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.leaf-icon {
  font-size: 20px;
}

.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

/* 订单筛选 */
.orders-filter {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-tabs {
  display: flex;
  gap: 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-tab {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.filter-tab:hover {
  color: #10b981;
}

.filter-tab.active {
  color: #10b981;
  border-bottom-color: #10b981;
}

.tab-count {
  background: #10b981;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  min-width: 20px;
  text-align: center;
}

.filter-actions {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.time-select {
  width: 150px;
}

/* 订单列表 */
.empty-orders {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 12px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-text {
  color: #6b7280;
  font-size: 18px;
  margin-bottom: 20px;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-number {
  font-weight: 600;
  color: #1f2937;
}

.order-time {
  color: #6b7280;
  font-size: 14px;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
}

.status-badge.pending {
  background: #fef3c7;
  color: #d97706;
}

.status-badge.paid {
  background: #dbeafe;
  color: #1d4ed8;
}

.status-badge.shipped {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.completed {
  background: #f3f4f6;
  color: #6b7280;
}

.status-badge.cancelled {
  background: #fee2e2;
  color: #dc2626;
}

/* 订单商品 */
.order-products {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.product-spec {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.product-quantity {
  color: #6b7280;
  font-weight: 500;
  min-width: 40px;
  text-align: center;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #ef4444;
  min-width: 80px;
  text-align: right;
}

/* 订单统计 */
.order-summary {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

.summary-info {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #6b7280;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: #ef4444;
}

/* 订单操作 */
.order-actions {
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.payment-timer {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 16px;
  color: #ef4444;
  font-weight: 500;
}

.timer-count {
  font-weight: 600;
}

/* 支付对话框 */
.payment-dialog {
  text-align: center;
}

.payment-info {
  margin-bottom: 20px;
}

.payment-amount {
  font-size: 18px;
  margin-bottom: 12px;
}

.amount {
  color: #ef4444;
  font-weight: 600;
  font-size: 24px;
}

.payment-method {
  font-size: 14px;
  color: #6b7280;
}

.payment-timer {
  background: #fff7ed;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.timer {
  color: #ef4444;
  font-weight: 600;
}

.payment-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 退款对话框样式 */
.refund-dialog {
  padding: 20px 0;
}

.order-refund-info {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #10b981;
}

.order-refund-info .order-number {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.order-refund-info .order-amount {
  color: #ef4444;
  font-weight: 500;
}

/* 图片上传区域 */
.image-upload-section {
  width: 100%;
}

.image-preview-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
  gap: 12px;
  margin-top: 16px;
}

.image-preview-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}

/* 表单验证样式 */
.el-form-item.is-required .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 退款标记样式 */
.refund-badge {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  margin-right: 8px;
  animation: pulse 2s infinite;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

/* 评分对话框样式 */
.rating-dialog-content {
  padding: 10px 0;
}

.rating-header {
  text-align: center;
  margin-bottom: 24px;
}

.rating-header h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
}

.rating-subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.order-info-rating {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  border-left: 4px solid #10b981;
}

.order-products-rating {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item-rating {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image-rating {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  object-fit: cover;
}

.product-info-rating h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.product-info-rating p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.rating-section {
  text-align: center;
  margin-bottom: 24px;
}

.rating-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  font-weight: 500;
}

.rating-stars {
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.rating-text {
  font-size: 14px;
  color: #666;
  min-height: 20px;
}

.rating-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.submit-rating-btn {
  min-width: 140px;
}

/* 已评分按钮样式 */
.el-button--success.is-disabled {
  background-color: #f0f9ff;
  border-color: #bae6fd;
  color: #0ea5e9;
}

/* 评分星星样式优化 */
.rating {
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
  gap: 0.5rem;
  --stroke: #d1d5db;
  --fill: #fbbf24;
  --fill-active: #f59e0b;
}

.rating input {
  appearance: unset;
}

.rating label {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.rating label:hover {
  transform: scale(1.1);
}

.rating svg {
  width: 2.5rem;
  height: 2.5rem;
  overflow: visible;
  fill: transparent;
  stroke: var(--stroke);
  stroke-linejoin: bevel;
  stroke-dasharray: 12;
  transition: stroke 0.2s, fill 0.3s;
}

.rating label:hover svg,
.rating input:checked ~ label svg {
  stroke: var(--fill-active);
}

.rating input:checked ~ label svg {
  fill: var(--fill);
  stroke: var(--fill-active);
  animation: yippee 0.5s ease;
}

@keyframes yippee {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 订单状态区域调整 */
.order-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 取消退款按钮样式 */
.el-button--danger {
  background: #ff6b6b;
  border-color: #ff6b6b;
}

.el-button--danger:hover {
  background: #ff5252;
  border-color: #ff5252;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .image-preview-list {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .image-preview-item {
    width: 100%;
    height: 80px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-tabs {
    justify-content: center;
  }
  
  .filter-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .product-item {
    flex-wrap: wrap;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .summary-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-end;
  }
}
</style>